# cc2 <http://cc2.berlios.de/> is a web application to drive
# grassroot initiatives.
#
# Copyright (C) 2009 Alberto Granzotto <agranzot@gmail.com>
# Copyright (C) 2009 Stefano Cavallari <stefano@cavallari.cjb.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import turbogears as tg
import cherrypy
import logging
log = logging.getLogger(__name__)

from creoleparser.dialects import create_dialect, creole11_base
from creoleparser.core import Parser

wiki_base_url = tg.config.get('turbowiki.wiki_base_url', '/wiki')

params = dict(
    wiki_links_base_url=wiki_base_url+'/view/',
    interwiki_links_base_urls=dict(wikicreole='/interwiki/view/'))

wiki_parser = Parser(dialect=create_dialect(creole11_base, **params))
wiki_validator = tg.validators.Regex(r'^[A-z0-9._-]*$',
    not_empty=True, max=64, strip=True)

def get_user_ip():
    '''Return the ip of the visitor.'''
    headers = cherrypy.request.headers
    ip = headers.get('X-FORWARDED-FOR', headers['Remote-Addr'])
    return ip

def get_user_id():
    '''If the user is logged return the id of the user, if the
    user is anonymous return None.
    '''
    if tg.identity.current.anonymous:
        user_id = None
    else:
        user_id = tg.identity.current.user.user_id
    return user_id

def get_locale():
    locale = tg.i18n.utils.get_locale()
    if '_' in locale:
        locale = locale.split('_')[0]
    return locale

def get_user_name(user_id):
    return user_id

def get_user_name_url(user_id):
    return '%s/view/usr.%s' % (wiki_base_url, user_id)

def post_edit_hook(**kw): pass

def load_hook(hook_name, if_none=None):
    try:
        hook = tg.util.load_class(
            tg.config.get('turbowiki.hooks.%s' % hook_name, None))
        log.info('successfully loaded custom hook %s' % hook_name)
        return hook
    except AttributeError:
        log.warning('invalid configuration value for '
                'turbowiki.hooks.%s, '
                'loaded default hook.' % hook_name)
    except AssertionError:
        log.info('loaded default hook %s' % hook_name)
    return if_none

get_user_name = load_hook('get_user_name', get_user_name)
get_user_name_url = load_hook('get_user_name_url', get_user_name_url)
post_edit_hook = load_hook('post_edit', post_edit_hook)
